package com.imooc.producer;

import lombok.RequiredArgsConstructor;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

@Service("producerService")
@RequiredArgsConstructor
public class ProducerService {

    private final RocketMQTemplate rocketMQTemplate;

    public void sendMsg() {
        for (int i = 0; i < 10; i++) {
            rocketMQTemplate.convertAndSend("myrocketmq", "你好，RocketMq" + i);
        }
    }

    /**
     * 会阻塞线程，性能相对差点，可靠性高，比如：短信通知，邮件通知，站内重要信息通知
     * 发送同步消息
     */
    public void sendSyncMessage() {
        for (int i = 0; i < 10; i++) {
            SendResult myrocketmq = rocketMQTemplate.syncSend("myrocketmq", "发送同步消息" + i);
            System.out.println(myrocketmq);
        }
    }

    /**
     * producer向broker发送消息时指定消息发送成功及发送异常的回调方法，调用API后立即返回，
     * producer发送消息线程不阻塞，发送消息成功或失败的回调任务在一个新的线程中执行
     * 行对发送同步消息，异步消息性能更高，可靠性略差，适合对响应时间要求高的业务场景
     */
    public void sendAsyncMessage() {
        for (int i = 0; i < 10; i++) {
            rocketMQTemplate.asyncSend("myrocketmq", "异步发送消息" + i, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println("发送成功！");
                }

                @Override
                public void onException(Throwable throwable) {
                    System.out.println("发送失败");
                }
            });
        }
    }

    /**
     * producer向broker发送消息，执行Api时直接返回，不等待broker服务器的结果
     * 不特别关心发送结果的场景，举例：日志发送
     * 发送单向消息
     */
    public void sendOneWayMessage() {
        for (int i = 0; i < 10; i++) {
            rocketMQTemplate.sendOneWay("myrocketmq", "单向消息" + i);
        }
    }

    /**
     * 发送同步顺序消息
     */
    public void sendOrderlyMessage() {
        // hashkey,计算消息发送到哪一消息队列，一般是订单ID，产品ID等
        rocketMQTemplate.syncSendOrderly("myrocketmq", "1, 创建", "1");
        rocketMQTemplate.syncSendOrderly("myrocketmq", "2, 支付", "2");
        rocketMQTemplate.syncSendOrderly("myrocketmq", "3, 完成", "3");

        rocketMQTemplate.syncSendOrderly("myrocketmq", "4, 创建", "4");
        rocketMQTemplate.syncSendOrderly("myrocketmq", "5, 支付", "5");
        rocketMQTemplate.syncSendOrderly("myrocketmq", "6, 完成", "6");
    }

    /**
     * 发送延迟消息
     */
    public void sendDelayMessage() {
        rocketMQTemplate.syncSend("myrocketmq", MessageBuilder.withPayload("rocketmq延迟1秒消息").build(), 1000, 1);
        rocketMQTemplate.syncSend("myrocketmq", MessageBuilder.withPayload("rocketmq延迟5秒消息").build(), 5000, 2);
        rocketMQTemplate.syncSend("myrocketmq", MessageBuilder.withPayload("rocketmq延迟10秒消息").build(), 10000, 3);
    }

}
